package com.xb.loan.cashier.biz.task.wechat;

import com.xb.loan.cashier.biz.dao.bean.CashierPayChannel;
import com.xb.loan.cashier.biz.pay.wechat.WeChatConst;
import com.xb.loan.cashier.biz.pay.wechat.util.RandomStringGenerator;
import com.xb.loan.cashier.biz.pay.wechat.util.WeChatSignature;
import com.xb.loan.cashier.biz.pay.wechat.util.httpClient.HttpsCerRequest;
import com.xb.loan.cashier.biz.task.ThirdAccountChargeTask;
import com.xb.loan.cashier.biz.task.bean.ThirdAccountBean;
import com.xb.loan.cashier.biz.task.bean.ThirdAccountChargeBean;
import com.xb.loan.cashier.biz.util.XMLUtil;
import com.xb.loan.cashier.service.constant.ICashierEnumConst;
import com.xb.loan.util.json.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 微信对账第三方查询
 * 微信在次日9点启动生成前一天的对账单，建议商户10点后再获取； 
 * @author zljun
 *
 * 2016年5月10日
 */
@Component(value="wechatAccountChargeTask")
@Scope(value="prototype")
public class WechatAccountChargeTask extends ThirdAccountChargeTask {
    
    private static final Logger logger = LoggerFactory.getLogger(WechatAccountChargeTask.class);


    @Override
    protected boolean hasThirdAccountTime() {
        return true;
    }

    @Override
    protected int getPayChannelType() {
        return ICashierEnumConst.CashierPayChannelType.WECHATPAY.getType();
    }

    @Override
    protected Map<String, ThirdAccountBean> getThirdAccountDatas(int pageNo, int pageSize, String day, CashierPayChannel channel) {
    	if (pageNo==2) {
			return null;
		}
        HashMap<String, ThirdAccountBean> result = new HashMap<String, ThirdAccountBean>();
        String payChannelId = channel.getPayChannelId();
        String signKey = channel.getMd5Key();
        String mchId = channel.getChannelUser();
        String payUrl = channel.getPayUrl()+"downloadbill";
        String datas = "";
        Map<String , Object> xmlObj = new HashMap<String , Object>();
        String appid = JsonUtils.fromJson(channel.getJsonConfig()).get("appid").toString();
        xmlObj.put("appid", appid);//公众账号ID
        xmlObj.put("mch_id", mchId);//商户号
        xmlObj.put("nonce_str", RandomStringGenerator.getRandomStringByLength(32));//随机字符串
        xmlObj.put("bill_date", day);//对账单日期
        xmlObj.put("bill_type", "SUCCESS");//ALL，返回当日所有订单信息，默认值;SUCCESS，返回当日成功支付的订单;REFUND，返回当日退款订单;撤销的订单
        String sign = WeChatSignature.getSign(xmlObj, signKey);
        xmlObj.put("sign", sign);//签名
        try {
            HttpsCerRequest hr = new HttpsCerRequest();
			datas = hr.sendPost(payUrl, xmlObj);
			logger.info("WechatAccountChargeTask.getThirdAccountDatas result datas="+datas);
		} catch (Exception e) {
			logger.error("WechatAccountChargeTask.getThirdAccountDatas send fail",e);
		}
        //这里失败的时候是返回xml数据，成功的时候反而返回非xml数据
        try {
			Map<String, Object> map = XMLUtil.parse(datas.getBytes("UTF-8"));
			if (WeChatConst.TRADE_FAIL.equals(map.get("return_code").toString())) {
				logger.info("WechatAccountChargeTask.getThirdAccountDatas failMsg="+map.get("return_msg").toString());
			}
		} catch (Exception e) {
			//处理成功
			List<ThirdAccountBean> list = convert(datas);
			// 数据为空
			if(list==null || list.size()<1){
				logger.info("msg=数据为空 payChannelId="+payChannelId+" day="+day);
				return result;
			}
			for(ThirdAccountBean order : list){
				result.put(order.getOrderId(), order);
			}
		}
        return result;
    }
    
    private List<ThirdAccountBean> convert(String datas) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd");
        List<ThirdAccountBean> result = new ArrayList<ThirdAccountBean>();
        String titles = datas.substring(0, datas.indexOf("`"));
    	String contens = datas.substring(datas.indexOf("`")+1, datas.length());
    	int titlesLen = titles.split(",").length;
    	List<List<String>> resultList = new ArrayList<>();
    	contens = contens.replaceAll(",","");
    	List<String> contentList = new ArrayList<>();
    	contentList.addAll(Arrays.asList(contens.split("`")));
    	while(contentList.size()>0){
    		List<String> rowList = new ArrayList<>();
    		for (int i = 0; i < titlesLen; i++) {
    			if(contentList.size()==0)
    				break;
    			rowList.add(contentList.remove(0));
    		}
    		resultList.add(rowList);
    	}
    	for (List<String> list : resultList) {
    		 ThirdAccountChargeBean order = new ThirdAccountChargeBean();
    		 order.setOrderIdThird(list.get(5));
             order.setOrderId(list.get(6));
             order.setMoney(Double.valueOf(list.get(6)));
           //TODO：没有匹配字段
//             order.setBuyAccount(buyer_account);
             try {
				order.setAccountDayThird(sdf1.format(sdf.parse(list.get(0))));
			} catch (ParseException e) {
				e.printStackTrace();
			}
             order.setAccountDay(null);
             order.setStatus(ThirdAccountBean.STATUS_SUCCESS);
             result.add(order);
		}
        return result;
    }
    
    public static void main(String[] args) {
    	String datas = "交易时间,公众账号ID,商户号,子商户号,设备号,微信订单号,商户订单号,用户标识,交易类型,交易状态,付款银行,货币种类,总金额,企业红包金额,商品名称,商户数据包,手续费,费率 `2016-03-10 10:08:52,`wx426b3015555a46be,`1225312702,`0,`,`1000120492201603103868926582,`122531270220160310100822,`oHZx6uCKaOM3_IxIhSCNE3iY8vRE,`JSAPI,`SUCCESS,`CITIC_CREDIT,`CNY,`0.01,`0.00,`test,`test,`0.00000,`0.60% `2016-03-10 00:08:30,`wx426b3015555a46be,`1225312702,`0,`,`1001400492201603103862756073,`122531270220160310000751,`oHZx6uEc_8mFX_QwPcGXQJVLqUb0,`NATIVE,`SUCCESS,`CFT,`CNY,`0.01,`0.00,`test,`test,`0.00000,`0.60%";
    	List<ThirdAccountBean> list = new WechatAccountChargeTask().convert(datas);
    	System.out.println(list.size());
	}

}
